package com.threefivework.mymall;

import com.threefivework.mymall.config.ProxyConfig;
import com.threefivework.mymall.config.RestConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;

@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.threefivework.mymall.*.mapper")
public class MymallApplication {

	/**
	 * 启动的时候要注意，由于我们在controller中注入了RestTemplate，所以启动的时候需要实例化该类的一个实例
	 */
	@Autowired
	private RestTemplateBuilder builder;

	@Autowired
	private ProxyConfig proxyConfig;

	@Autowired
	private RestConfig restConfig;

	@Value("${rest.socketTimeout}")
	private Integer socketTimeout;

	/**
	 * 使用RestTemplateBuilder来实例化RestTemplate对象，spring默认已经注入了RestTemplateBuilder实例
	 */
	@Bean
	public RestTemplate restTemplate() {
		return builder.build();
	}

//	@Bean
//	public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
//		return new RestTemplate(factory);
//	}

	@Bean
	public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		//单位为ms
		factory.setReadTimeout(restConfig.getReadTimeout());
		//单位为ms
		factory.setConnectTimeout(restConfig.getConnectTimeout());
		//是否启用代理设置
		if (proxyConfig.getEnabled()) {
			SocketAddress socketAddress = new InetSocketAddress(proxyConfig.getHost(), proxyConfig.getPort());
			Proxy proxy = new Proxy(Proxy.Type.HTTP, socketAddress);
			factory.setProxy(proxy);
		}
		return factory;
	}

	public static void main(String[] args) {
		SpringApplication.run(MymallApplication.class, args);
	}
}
